<template>
  <BottomDrawer :visible="addVisible" :title="'排班维护'" :width="900" @close="addVisible = false">
    <div class="schedulingUpdata">
      <el-table :data="tableData" style="width: 100%"  ref="multipleTableRef" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="shiftName" label="班次" width="122px" />
        <el-table-column prop="name" label="时段" width="122px">
          <template #default="props">
            {{ props.row.startTime }}-{{ props.row.endTime }}
          </template>
        </el-table-column>
        <el-table-column prop="address" label="科室" width="124px">
          <template #default="props">
            <el-select v-model="props.row.deptId" class="m-2" filterable @change="getRoomListApi(props.row.deptId, props.$index,'')"
              placeholder="科室" style="width: 100%">
              <el-option v-for="item in deptList" :key="item.deptId" :label="item.deptName" :value="item.deptId" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="诊室" width="125px">
          <template #default="props">
            <el-select v-model="props.row.roomId" filterable class="m-2" placeholder="诊室" style="width: 100%">
              <el-option v-for="item in roomListTable[props.$index]" :key="item.roomId" :label="item.roomName"
                :value="item.roomId" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="是否请假">
          <template #default="props">
            <div style="display: flex;">
              <el-switch v-model="props.row.isLeave" class="ml-2" active-value="1" inactive-value="0" 
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #DCDCDC" />
              <el-time-picker v-model="props.row.leaveStartTime" :disabled="props.row.isLeave !== '1'" style="width: 100px;margin-left: 10px;" format="HH:mm"
                value-format="HH:mm" arrow-control placeholder="请假开始时间" />
              <el-time-picker v-model="props.row.leaveEndTime" :disabled="props.row.isLeave !== '1'" style="width: 100px;margin-left: 10px;" format="HH:mm"
                value-format="HH:mm" arrow-control placeholder="请假结束时间" />
            </div>

          </template>

        </el-table-column>

      </el-table>
    </div>
    <errorList ref="errorListRef"></errorList>
    <template #footer>
      <el-button @click="handleSubmit" type="primary">确 定</el-button>
      <el-button @click="addVisible = false">取 消</el-button>
    </template>
  </BottomDrawer>
</template>

<script setup lang="ts">

import type { FormRules, ElTree } from 'element-plus';
import type { ShiftFrom, ShiftRole, SchedulingRole, ScheduleList, SchedulingItem,RangeForm } from '@/types/registrationSettings/index.ts';
import { deptGetSelectList } from '@/api/account'
import { getRoomList } from '@/api/clinic/account'
import {saveSchedule} from '@/api/register'
import { ElTable } from 'element-plus'
import errorList from './errorList.vue';
const errorListRef = ref<InstanceType<typeof errorList>>();


import { getShiftList } from '@/api/register/index';
import dayjs from 'dayjs';
import { de } from 'element-plus/es/locales.mjs';
const formInline = ref<ShiftFrom>({
  shiftName: '',
  pageNo: 1,
  pageSize: 1000,
});

const multipleSelection = ref<SchedulingItem[]>([])
const handleSelectionChange = (val: SchedulingItem[]) => {
  multipleSelection.value = val
}
// 获取序列列表
const tableData = ref<SchedulingItem[]>([]);
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const roomListTable = ref<any>([])
const getShiftLists = async () => {
  const res = await getShiftList(formInline.value)
  if(res.code !== '200') {
    //ElMessage.error(res.msg);
    return;
  } 
  for (let index = 0; index < res.data.list.length; index++) {
    const item = res.data.list[index];
    if (item) {
      let info:any = {
        shiftId: item.shiftId ?? 0,
        shiftName: item.shiftName,
        startTime: item.startTime,
        endTime: item.endTime,
        leaveStartTime: '',
        leaveEndTime: '',
        isLeave: '0',
        roomId: null as number | null,
        deptId: null as number | null
      }
      if(tableIiem.value.detailList?.length){
          for (let index = 0; index < tableIiem.value.detailList.length; index++) {
            roomListTable.value.push([])
          }
          for (let index2 = 0; index2 < tableIiem.value.detailList.length; index2++) {
            const element = tableIiem.value.detailList[index2];
            if(element && element.shiftId == item.shiftId){
              info.deptId = element.deptId
              info.isLeave = element.isLeave
              info.roomId = element.roomId
              info.leaveEndTime = element.leaveEndTime ?? ''
              info.leaveStartTime = element.leaveStartTime ?? ''
              info.detailId = element.detailId
            }
            
          }
      }
    

      tableData.value.push(info);


    }
  }
  tableData.value.forEach((element,index)=>{
    console.log(element,'element');
    
    if(element.deptId){
      //console.log(element,'e');
      multipleTableRef.value!.toggleRowSelection(element, undefined)    
      getRoomListApi(element.deptId,index,'1')
    }else{
      element.deptId = deptId.value
      getRoomListApi(element.deptId,index,'1')

    }
  })
  // //console.log(tableData.value);

  // tableData.value = res.list
};

const getRoomListApi = async (deptId: any, index: number,t:string) => {
  let res = await getRoomList({ deptId: deptId })
  if(res.code !== '200') {
    //ElMessage.error(res.msg);
    return;
  }
  roomListTable.value[index] = res.data.list
  if (tableData.value[index] && !t) {
    tableData.value[index].roomId = null
  }
  
  // roomListTable.value[index] 

}


const tableIiem = ref<SchedulingRole>({
  scheduleId: '',
  workDate: '',
  empId: 0,
  detailList:[]
})

const deptId = ref<any>(0);
defineExpose<{
  open: (row: SchedulingRole, value: ScheduleList) => void;

}>({
  open: (row: any, value: ScheduleList) => {
    tableIiem.value.workDate = value.workDate || ''
    tableIiem.value.empId = row.empId
    tableIiem.value.scheduleId = row.scheduleId
    tableIiem.value.detailList = value.detailList
    deptId.value = row.deptId;
    addVisible.value = true;
    roomListTable.value = []
    tableData.value = []
    getDeptGetSelectList()
    getShiftLists()


  },

});

const addVisible = ref(false);
const deptList = ref<any>([])
const getDeptGetSelectList = async () => {
  let res = await deptGetSelectList()
  if(res.code !== '200') {
    //ElMessage.error(res.msg);
    return;
  }
  deptList.value = res.data
}


const handleSubmit = async () => {
  let bool = true
  //console.log('submit',multipleSelection.value);
  // if(!multipleSelection.value.length){
  //   ElMessage({
  //         message: '排班信息不能为空！',
  //         type: 'warning',
  //   })
  // }
  for (let index = 0; index < multipleSelection.value.length; index++) {
    let item = multipleSelection.value[index];
    if (item) {
      if (!item.deptId) {
        ElMessage({
          message: '科室不能为空！',
          type: 'warning',
        })
        return
      }
      if (!item.roomId) {
        ElMessage({
          message: '诊室不能为空！',
          type: 'warning',
        })
        return
      }
      if (item.isLeave == '1') {
        if (!item.leaveStartTime) {
          ElMessage({
            message: '请假开始不能为空！',
            type: 'warning',
          })
          return
        }
        if (!item.leaveEndTime) {
          ElMessage({
            message: '请假结束不能为空！',
            type: 'warning',
          })
          return
        }
      }
    }
  }

  tableIiem.value.detailList = multipleSelection.value

  let res = await saveSchedule(tableIiem.value)
  if(res.code == '200'){
      if(res.data.isCancel == '1'){
        errorListRef.value?.open(res)
      }else{
        //模拟需要退号
        // let data:RangeForm = {
        //   "shiftId": 4, //班次ID；必须参数
        //   "doctorId": null, //医生ID 员工请假场景需要给
        //   "rangeList": [
        //     {
        //     "start": "08:30",
        //     "end": "12:30"
        //     }
        //   ],  
        // }
        // errorListRef.value?.open(data)
        ElMessage({
          message: '操作成功',
          type: 'success',
        }) 
        addVisible.value = false
        closeDrawer()
      }
  }else{
    
  }


};
const emit = defineEmits(['closeDrawer']);
const closeDrawer = () => {
  addVisible.value = false
  emit('closeDrawer');
};

</script>
<style lang="scss">
.schedulingUpdata .el-input__wrapper {
  border-radius: 6px;
}
</style>
<style lang="scss" scoped>
.tree-box {
  border: 2px solid #e1e1e1;
  height: 300px;
  width: 451px;
  margin-top: 10px;
  overflow-y: auto;
}
</style>
